package com.siruier.boss.ui.activity.login

import android.view.View
import com.siruier.boss.api.core.MD5Util
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.loginApi
import com.siruier.boss.databinding.ActivityForgetPasswordBinding
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.ext.toastMessageLong
import com.siruier.boss.ui.ext.value
import com.siruier.boss.ui.utils.variableView

class ForgetPasswordActivity : BaseActivity<ActivityForgetPasswordBinding>() {

    override fun initView() {
        bindViewClick(vb.tbVcode, vb.buttonConfirm)
        variableView {
            addTextView(vb.etPhone)
            addTextView(vb.etPasswrod)
            addTextView(vb.etVcode)
            addOnValidationResultListener(vb.buttonConfirm)
            addOnValidationInterceptListener(this@ForgetPasswordActivity::validator)
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.tbVcode -> {
                launchUI({ loginApi.smsSend(vb.etPhone.value, "mdLgnPwd").toData() }, ApiObserver(this) {
                    vb.tbVcode.start()
                })
            }
            vb.buttonConfirm -> {
                launchUI({ loginApi.updatePwd(vb.etPhone.value, MD5Util.md5(vb.etPasswrod.value), vb.etVcode.value).toData() }, ApiObserver(this) {
                    "找回成功".toastMessageLong()
                    finish()
                })
            }
        }
    }

    private fun validator(view: View) = when (view) {
        vb.etPhone -> vb.tbVcode.enable(vb.etPhone.length() == 11)
        vb.etVcode -> vb.etVcode.length() == 4
        else -> null
    }
}